<template>
  <div>
    <h2 v-if="firstView">输入用户名搜索</h2>
    <h2 v-if="loading">LOADING...</h2>
    <h2 v-if="errorMsg">{{errorMsg}}</h2>
    <div class="row">
      <div class="card" v-for="(user, index) in users" :key="index">
        <a href="https://github.com/reactjs" target="_blank">
          <img :src="user.avatar_url" style="width: 100px;">
        </a>
        <p class="card-text">{{user.name}}</p>
      </div>
    </div>
  </div>
</template>
<script>
import PubSub from "pubsub-js"
import axios from "axios"
export default {
  data(){
    return{
      firstView:true,
      loading:false,
      users:null,
      errorMsg:''
    }
  },
  mounted(){
    //订阅搜索的消息
    PubSub.subscribe('search',(msg,searchName)=>{
      const url=`https://api.github.com/search/users?q=${searchName}`
      this.firstView=false
      this.loading=true
      // this.users=false
      axios.get(url).then(res=>{
        const result=res.data
        const users=result.items.map(item=>({
          url:item.html_url,
          avatar_url:item.avatar_url,
          name:item.login
        }))
        this.loading=false
        this.users=users
      })
    })
  },
}
</script>


<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>

</style>
